<?php
/* required libraries */
require('./library/strings.php');
require('./library/classes.php');

/* create the index and display it */
$index = new CABLEindex();
echo $index->source;

/* classes */
class CABLEindex
{
	public	$source;
	public	$config;
	public	$db;
	public	$user;

	private	$cache;
	private $plugins	= array();
	private	$template;
	private	$messages = array();
	private $error = false;
	
	public function __construct()
	{
		$this->error = true;
		$this->config = new CABLEconfig();
		if ($this->config->error === false)
		{
			$this->db = new CABLEdb();
			if ($this->db->Connect($this->config->values['DbServer'],$this->config->values['DbUsername'],$this->config->values['DbPassword'],$this->config->values['DbName']))
			{
				$this->user	= new CABLEuser($this->config,$this->db);
				if ($this->user->error === false)
					$this->error = false;
			}
		}
		
		/* check the cache, create new if necessary */
		if ($this->error === false)
		{
			/* initialize cache */
			$this->cache = new CABLEcache('index',$this->config);
			
			/* see if there's a template in the cache */
			if (($cache = $this->cache->GetCache($this->user->timestamp)) === false)
			{
				/* build the index from scratch */
				$this->source = $this->BuildIndex(true);
				
				/* write the static template contents to the cache */
				$this->cache->WriteCache($this->user->timestamp,$this->template->cache);
			}
			else
			{
				$this->template = new CABLEtemplate($cache);
				$this->source = $this->BuildIndex(false);
			}
			
			if ($this->source === false)
				$this->error = true;
		}
		
		/* message consolidation */
		if (($this->config->values['ErrorThreshold'] > 0) || ($this->error !== false))
		{
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->config->messages);
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->db->messages);
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->user->messages);
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->cache->messages);
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->template->messages);
			
			$this->source = CABLE_MakeMessages($this->messages,$this->config->values['ErrorThreshold']).$this->source;
		}
		
		return null;
	}
	
	private	function BuildIndex($new)
	{
		if ($new)
		{
			/* load template from db */
			$this->template = new CABLEtemplate($this->config,$this->db,$this->config->values['ThemeName'],'index');
			if ($this->template->error)
				return false;
						
			/* execute query */
			$table = "cable_".$this->config->values['TablePrefix']."_entries";
			$query = "SELECT timestamp,author,title,data FROM $table WHERE (timestamp <= ".$this->user->timestamp.') AND (visible=1) ORDER BY timestamp DESC LIMIT '.$this->config->values['IndexEntries'];
			
			if (($result = mysql_query($query,$this->db->db_link)) === false)
			{
				$this->messages[0][] = str_replace('<id>',mysql_error($this->db->db_link),CABLE_ERROR_DATABASE_REQUEST);
				return false;
			}
			
			/* load entry data results into array */
			$entries = array();
			while ($row = mysql_fetch_assoc($result))
			{
				/* extract serialized entry data */
				$data = unserialize($row[data]);
				unset($row[data]);
				foreach($data as $key => $value)
				{
					if (!isset($entry_array[$key]))
					{
						if (is_string($value))
							$entry_array[$key] = rawurldecode($value);
						else
							$entry_array[$key] = $value;
					}
				}
				
				$entries[$row[timestamp]] = array_merge($data,$row);
			}
	
			if ($this->config->values['IndexSort'] != 'descending')
				ksort($entries);
		}
		else
			$entries = array('cached'=>true);
			
		/* load plugins and run initialization routines */
		$plugin_names = explode(',',$this->config->values['IndexPlugins']);
		foreach($plugin_names as $name)
		{
			$this->plugins[$name] = new CABLEplugin($name,$this->config,$this->db,$this->user);
			$this->plugins[$name]->Connect($this->template,$entries);
			$this->plugins[$name]->Execute('open');
			
			/* retrieve plugin messages */
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->plugins[$name]->messages);
			unset($this->plugins[$name]->messages);
			
			/* bail if necessary */
			if ($this->plugins[$name]->abort)
				break;
		}

		if ($new) /* only run plugin entries if we're creating a new template */
		{
			/* drop entries marked for deletion */
			foreach($entries as $timestamp => $entry_data)
				if ($entry_data[delete])
					unset($entries[$timestamp]);
			
			/* iterate through entry data */
			$counter = 0;
			foreach($entries as $entry_data)
			{
				$entry_data[counter] = $counter;
				$entry_data[num] = count($entries);
				
				/* run plugin routines */
				foreach($plugin_names as $name)
				{
					$this->plugins[$name]->Connect($this->template,$entry_data);
					$this->plugins[$name]->Execute('');
					
					/* retrieve plugin messages */
					$this->messages = CABLE_MessageArrayCombine($this->messages,$this->plugins[$name]->messages);
					unset($this->plugins[$name]->messages);
					
					/* bail if necessary */
					if ($this->plugins[$name]->abort)
						break;
				}
				
				$counter++;
			}
		}
		
		/* run plugin closing routines */
		foreach($plugin_names as $name)
		{
			$this->plugins[$name]->Connect($this->template,$entries);
			$this->plugins[$name]->Execute('close');
			
			/* retrieve plugin messages */
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->plugins[$name]->messages);
			unset($this->plugins[$name]->messages);
			
			/* bail if necessary */
			if ($this->plugins[$name]->abort)
				break;
			
			/* clean up */
			unset($this->plugins[$name]);
		}
		
		return $this->template->Render();
	}
}

?>